/*
 * @Author: hongbin
 * @Date: 2022-11-19 17:26:59
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-19 18:46:33
 * @Description: 注册用户
 */
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../../src/api/utils";
import DB from "../mongodb";
import { receiveRequest } from "../utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    if (!receiveRequest(req, res, "POST")) return;
    const db = await DB;
    console.log(req.body);

    if (!VerifyFields.has(req.body, ["name", "password"])) {
        return res.status(500).json("缺少关键字段");
    }
    const userInfo = { ...req.body };
    delete userInfo["conformPassword"];

    // name是否重复
    const list = await db.collection("userInfo").find({ name: userInfo.name }).toArray();
    if (list.length) {
        return res.status(200).json({ data: null, msg: "用户名重复", code: -1 });
    }

    const insert = await db.collection("userInfo").insertOne(userInfo);
    console.log(insert);
    if (insert.acknowledged) {
        res.status(200).json({ data: insert.insertedId });
        return;
    }
    res.status(200).json({ data: null, msg: "插入失败", code: -1 });
}
